//
//  BVHttpManagerHelper.m
//  VerticalP
//
//  Created by 农民 on 2017/7/27.
//  Copyright © 2017年 农民. All rights reserved.
//

#import "BVHttpManager.h"
#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"

#ifdef DEBUG
#define HttpLog(...) NSLog(@"%s 第%d行 \n %@\n\n",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#else
#define HttpLog(...)
#endif

@implementation BVHttpManager

static AFHTTPSessionManager *_manager;
static BVHttpManager *manager = nil;

+(instancetype)sharedNetManager{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[BVHttpManager alloc] init];
        
    });
    return manager;
}

+ (void)initialize{
    
    _manager = [AFHTTPSessionManager manager];
    //设置请求参数的类型:JSON (AFJSONRequestSerializer,AFHTTPRequestSerializer)
    _manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //设置请求的超时时间
    _manager.requestSerializer.timeoutInterval = 15.0f;
    //设置服务器返回结果的类型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer)
    //_manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*", nil];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
}

#pragma mark - 发起网络请求 ,无缓存
- (void)requstUrl:(NSString *)URL
           method:(NetWorkMethod)method
       parameters:(NSDictionary *)parameters
          success:(HttpRequestSuccess)success
          failure:(HttpRequestFailed)failure{
    
    switch (method) {
        case Get:{
            [self GET:URL parameters:parameters success:^(id responseObject) {
                success(responseObject);
            } failure:^(NSError *error) {
                failure(error);
            }];
        }
            break;
        case Post:{
            [self POST:URL parameters:parameters success:^(id responseObject) {
                success(responseObject);
            } failure:^(NSError *error) {
                failure(error);
            }];
        }
            break;
        case Put:{
            [self PUT:URL parameters:parameters success:^(id responseObject) {
                success(responseObject);
            } failure:^(NSError *error) {
                failure(error);
            }];
        }
            break;
        case Delete:{
            [self DELETE:URL parameters:parameters success:^(id responseObject) {
                success(responseObject);
            } failure:^(NSError *error) {
                failure(error);
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark - GET请求无缓存
- (void)GET:(NSString *)URL
 parameters:(NSDictionary *)parameters
    success:(HttpRequestSuccess)success
    failure:(HttpRequestFailed)failure
{
    
    [_manager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success ? success(responseObject) : nil;
        HttpLog(@"responseObject = %@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure ? failure(error) : nil;
        HttpLog(@"error = %@",error);
    }];
}

#pragma mark - POST请求无缓存
- (void)POST:(NSString *)URL
  parameters:(NSDictionary *)parameters
     success:(HttpRequestSuccess)success
     failure:(HttpRequestFailed)failure
{
    [_manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success ? success(responseObject) : nil;
        
        HttpLog(@"responseObject = %@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure ? failure(error) : nil;
        
        HttpLog(@"error = %@",error);
    }];
}
#pragma mark - PUT请求无缓存
- (void)PUT:(NSString *)URL
        parameters:(NSDictionary *)parameters
            success:(HttpRequestSuccess)success
                failure:(HttpRequestFailed)failure{
    
    [_manager PUT:URL parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success ? success(responseObject) : nil;
        
        HttpLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure ? failure(error) : nil;
        
        HttpLog(@"error = %@",error);
    }];
}

#pragma mark - DELETE请求无缓存
- (void)DELETE:(NSString *)URL
    parameters:(NSDictionary *)parameters
       success:(HttpRequestSuccess)success
       failure:(HttpRequestFailed)failure{
    
    [_manager DELETE:URL parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success ? success(responseObject) : nil;
        
        HttpLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure ? failure(error) : nil;
        
        HttpLog(@"error = %@",error);
    }];
    
}

#pragma mark - 上传图片文件
- (void)uploadWithImage:(NSString *)URL
             parameters:(NSDictionary *)parameters
                 images:(NSArray<UIImage *> *)images
                   name:(NSString *)name
               progress:(HttpProgress)progress
                success:(HttpRequestSuccess)success
                failure:(HttpRequestFailed)failure
{

    [_manager POST:URL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩-添加-上传图片
        [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@%d.jpg",str,((arc4random() % 501) + 500)];
            
            //压缩图片
            
            NSData *imgData = UIImageJPEGRepresentation(image, 0.7);
            //拼接data
            if (imgData != nil) {
                [formData appendPartWithFileData:imgData name:@"pic[]" fileName:fileName mimeType:@"image/*"];
            }
            
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        progress ? progress(uploadProgress) : nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success ? success(responseObject) : nil;
        HttpLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure ? failure(error) : nil;
        HttpLog(@"error = %@",error);
    }];
}


@end
